package com.hboxs.asl.wechat.payment;

import com.hboxs.asl.wechat.payment.base.WxPayApi;
import com.hboxs.asl.wechat.payment.base.WxPayData;
import com.hboxs.asl.wechat.payment.base.WxPayException;
import com.hboxs.asl.wechat.payment.base.WxPayNotify;
import org.apache.log4j.Logger;

/**
 * Created by study on 8/10/2015.
 */
public class WxPayResultNotify extends WxPayNotify {
    protected Logger logger = Logger.getLogger(getClass());


    @Override
    public WxPayData processNotify(WxPayData notifyData) throws WxPayException {
        WxPayData res = new WxPayData();

        //检查支付结果中transaction_id是否存在
        if (!notifyData.isSet("transaction_id")) {
            //若transaction_id不存在，则立即返回结果给微信支付后台
            res.setValue("return_code", "FAIL");
            res.setValue("return_msg", "支付结果中微信订单号不存在");
            logger.error("The Pay result is error : " + res.toXml());
            return res;
        }

        String transaction_id = notifyData.getValue("transaction_id").toString();

        //查询订单，判断订单真实性
        if (!queryOrder(transaction_id)) {
            //若订单查询失败，则立即返回结果给微信支付后台
            res.setValue("return_code", "FAIL");
            res.setValue("return_msg", "订单查询失败");
            logger.error("Order query failure : " + res.toXml());
            return res;
        } else {
            //查询订单成功
            res.setValue("return_code", "SUCCESS");
            res.setValue("return_msg", "OK");
            logger.info("order query success : " + res.toXml());
            return res;
        }
    }

    /**
     * 查询订单
     *
     * @param transaction_id 交易ID
     * @return ture or false
     */
    private boolean queryOrder(String transaction_id) throws WxPayException {
        WxPayData req = new WxPayData();
        req.setValue("transaction_id", transaction_id);
        WxPayData res = WxPayApi.orderQuery(req);
        if (res.getValue("return_code").toString().equals("SUCCESS") &&
                res.getValue("result_code").toString().equals("SUCCESS")) {
            return true;
        } else {
            return false;
        }
    }
}
